package com.blogs.service.user.impl;

import com.blogs.common.constant.ErrorConstant;
import com.blogs.common.exception.BusinessException;
import com.blogs.common.utils.TaleUtils;
import com.blogs.domain.db.SysUser;
import com.blogs.mapper.SysUserMapper;
import com.blogs.service.user.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * Description 用户管理业务层
 *
 * @author hubiao
 * @since 2020-09-27 15:00
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    /**
     * 这里会报错，但是并不影响
     */
    @Resource
    private SysUserMapper userDao;


    @Override
    public SysUser login(String username, String password) {

        if (StringUtils.isEmpty( username ) || StringUtils.isEmpty( password )) {
            throw BusinessException.withErrorCode( ErrorConstant.Auth.USERNAME_PASSWORD_IS_EMPTY );
        }

        String pwd = TaleUtils.MD5encode( username + password );
        SysUser user = userDao.getUserInfoByCond( username, pwd );
        if (null == user) {
            throw BusinessException.withErrorCode( ErrorConstant.Auth.USERNAME_PASSWORD_ERROR );
        }
        return user;
    }

    @Override
    public SysUser getUserInfoById(Integer uid) {
        return userDao.getUserInfoById( uid );
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateUserInfo(SysUser user) {
        if (StringUtils.isEmpty( user.getId() )) {
            throw BusinessException.withErrorCode( "用户编号不能为空" );
        }
        return userDao.updateUserInfo( user );
    }

    /**
     * 根据用户名查找对象
     *
     * @param username
     * @return
     */
    @Override
    public SysUser selectByName(String username) {
        return userDao.selectByName( username );
    }
}
